<?php
namespace jy_guashop;
defined('BY_JYA') or exit('error');
/*
	门店代理
*/
class area extends \plugin{
	public function get_area_code($area){
		$address=$area['province'];
		$oldaddress=$area['province'];
		if($area['city']){
			$address.=' '.$area['city'];
			$oldaddress.=' 直辖市';
		}
		if($area['district']){
			$address.=' '.$area['district'];
			$oldaddress.=' '.$area['district'];
		}
		if($area['street']){
			$address.=' '.$area['street'];
			$oldaddress.=' '.$area['street'];
		}
		$area_code=pdo_getcolumn('core_area',array('address'=>$address),'code');
		if(!$area_code){
			$isup=pdo_count('core_area',array(),'code');
			if($isup==0){
				require ROOT_D.'/update/update_area.php';
				$area_code=pdo_getcolumn('core_area',array('address'=>$address),'code');
			}else{
				$area_code=pdo_getcolumn('core_area',array('address'=>$oldaddress),'code');
				if($area_code){
					pdo_query('DROP TABLE IF EXISTS '.TABLE_PRE.'core_area;');
					require ROOT_D.'/update/update_area.php';
				}
			}
		}
		return $area_code;
	}
	/*
		申请成为区域代理
	*/
	public function apply_agent($mid,$area_code,$post=array()){
		if(!$area_code && !$post['is_duodai']){
			exi('获取区域code失败！','error');
		}
		$check=$this->getcolumn('area_agent',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'area_code'=>$area_code),'id');
		if($check){
			exi('您已经代理了该地区，请勿重复代理！','error');
		}
		if($post['area_type']!=4){
			$check=$this->getcolumn('area_agent',array('area_type'=>$post['area_type'],'uniacid'=>$_SESSION['uniacid'],'area_code'=>$area_code),'id');
			if($check){
				exi('该区域已存在代理！请更换！','error');
			}
		}
		$new_apply=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$mid,
			'status'=>0,
			'area_type'=>$post['area_type'],
			'area_code'=>$area_code,
			'area'=>ijson_encode($post['area']),
			'realname'=>$post['realname'],
			'mobile'=>$post['mobile'],
			'wechat'=>$post['wechat'],
			'title'=>$post['title'],
			'createtime'=>TIMESTAMP,
		);
		$this->insert('area_agent',$new_apply);
		$id=$this->insertid();
		return $id;
	}
	public function up_agent($mid,$area_code,$post=array()){
		$new_apply=array();
		if($area_code){
			$new_apply['area_code']	=$area_code;
			$new_apply['area_type']	=pdo_getcolumn('core_area',array('code'=>$area_code),'type');
		}
		$isadd=$this->get('area_agent',array('uniacid'=>$_SESSION['uniacid'],'area_type'=>$new_apply['area_type'],'area_code'=>$area_code));
		if($isadd && $isadd['id']!=$post['id']){
			exi('该区域已存在代理！请更换！！','error');
		}
		$this->update('area_agent',$new_apply,array('uniacid'=>$_SESSION['uniacid'],'id'=>$post['id']));
		return $mid;
	}
	/*
		审核区域代理
	*/
	public function check_agent($agent_id,$status,$remark=''){
		if(!$agent_id || !$status){
			return;
		}
		$area_agent=$this->get('area_agent',array('id'=>$agent_id));
		if(!$area_agent){
			return;
		}
		$update=array(
			'status'=>$status,
			'check_time'=>TIMESTAMP,
		);
		if($update['status']==1){
		}else{
			$update['remark']=$remark;
		}
		$this->update('area_agent',$update,array('id'=>$agent_id));
		return true;
	}
	public function set_parent($mid,$fromuser){
		$this->update('area_agent',array('agent_id'=>$fromuser),array('mid'=>$mid));
		return true;
	}
	/*
		禁用代理商
	*/
	public function stop_agent($agent_id){
		$this->update('area_agent',array('status'=>2),array('mid'=>$agent_id));
	}
	/*
		恢复代理商
	*/
	public function start_agent($agent_id){
		$this->update('area_agent',array('status'=>1),array('mid'=>$agent_id));
	}
	/*
		生成佣金
	*/
	function create($order){
        $this->areasetting=$this->plugin_setting('areasetting');
		if(!$this->areasetting['isopen']){
			return;
		}
		$this->order=$order;
        $order['address']=json_decode($order['address'],true);
        if($order['address'] && ($order['address']['name'] || $order['address']['adddress'])){
            $address=$order['address'];
        }else{
            $address=pdo_get('core_address',array('uniacid'=>$_SESSION['uniacid'],'id'=>$order['addressid']),'pcd');
        }
        $address=$address['pcd'];
        if(!is_array($address)){
            $address=json_decode($address,true);
        }
		if(!$address){
			return;
		}
		$this->commission_order=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$this->order['mid'],
			'ordersn'=>$this->order['ordersn'],
			'order_price'=>$this->order['price'],
			'commission_money'=>0,
			'type'=>1,
			'createtime'=>TIMESTAMP,
		);
		//佣金计算方式，是否扣除运费
		if($this->setting['commissiontype']==1){
			$this->commission_order['commission_price']=$this->order['price'];
		}else{
			$this->commission_order['commission_price']=$this->order['price']-$this->order['dispatchprice'];
		}
        $this->street_commission($address);
        $this->district_commission($address);
        $this->city_commission($address);
        $this->province_commission($address);
        //生成分销订单
		if($this->commission_order['isarea']){
			$indata=$this->commission_order;
			unset($indata['isarea']);
			$this->insert('fee_order',$indata);
		}
		return true;
	}
	public function province_commission($address){
		$area_code=pdo_getcolumn('core_area',array('address'=>$address['province']),'code');
		$this->commission_order['area_code']=$area_code;
		$agents=$this->getall('area_agent',array('uniacid'=>$_SESSION['uniacid'],'area_type'=>1,'status'=>1,'area_code'=>$area_code));
		if(!$agents){
			return;
		}
		foreach($agents as $agent){
			$member=$this->get('member',array('mid'=>$agent['mid']));
			if(!$member || $member['stop']){
				continue;
			}
			$this->create_commission($agent,1);
		}
	}
	public function city_commission($address){
		if(!$address['city']){
			return;
		}
		$area_code=pdo_getcolumn('core_area',array('address'=>$address['province'].' '.$address['city']),'code');
		$this->commission_order['area_code']=$area_code;
		$agents=$this->getall('area_agent',array('uniacid'=>$_SESSION['uniacid'],'area_type'=>2,'status'=>1,'area_code'=>$area_code));
		if(!$agents){
			return;
		}
		foreach($agents as $agent){
			$member=$this->get('member',array('mid'=>$agent['mid']));
			if(!$member || $member['stop']){
				continue;
			}
			$this->create_commission($agent,2);
		}
	}
	public function district_commission($address){
		if(!$address['district']){
			return;
		}
		$area_code=pdo_getcolumn('core_area',array('address'=>$address['province'].' '.$address['city'].' '.$address['district']),'code');
		$this->commission_order['area_code']=$area_code;
		$agents=$this->getall('area_agent',array('uniacid'=>$_SESSION['uniacid'],'area_type'=>3,'status'=>1,'area_code'=>$area_code));
		if(!$agents){
			return;
		}
		foreach($agents as $agent){
			$member=$this->get('member',array('mid'=>$agent['mid']));
			if(!$member || $member['stop']){
				continue;
			}
			$this->create_commission($agent,3);
		}
	}
	public function street_commission($address){
		if(!$address['street']){
			return;
		}
		$area_code=pdo_getcolumn('core_area',array('address'=>$address['province'].' '.$address['city'].' '.$address['district'].' '.$address['street']),'code');
		$this->commission_order['area_code']=$area_code;
		$agents=$this->getall('area_agent',array('uniacid'=>$_SESSION['uniacid'],'area_type'=>4,'status'=>1,'area_code'=>$area_code));
		if(!$agents){
			return;
		}
		foreach($agents as $agent){
			$member=$this->get('member',array('mid'=>$agent['mid']));
			if(!$member || $member['stop']){
				continue;
			}
			$this->create_commission($agent,4);
		}
	}
	/*
		给指定区域代理计算分红
	*/
	function create_commission($agent,$commission_level){
            $areasetting=$this->areasetting;
            $commission_per=$areasetting['fee_'.$commission_level];
			$money=0;
			$xuni_money=0;
			$order_price=$this->commission_order['commission_price'];
			$remark=array(
				'commission_level'=>$commission_level,
				'order_price'=>$order_price,
				'goods_commission'=>array(),
			);
			
			//先检查是否存在商品独立佣金规则，如果存在则对订单相应商品部分金额单独计算佣金
			foreach($this->order['goods'] as $goods){
				$ignore=$this->get('area_goods',array('goods_id'=>$goods['goodsid']));
				if($ignore['ignore']  || !$ignore['id']){
					if($ignore['ignore']){
						$order_price=$order_price-$goods['total_price'];
					}
					$canorder_price=1;
					continue;
				}
				if($canorder_price){
					$order_price=$order_price-$goods['total_price'];
				}
				$goods_commissions=$ignore['commissions']?json_decode($ignore['commissions'],true):array();
				$goods_commission_per=$goods_commissions['commission'.$commission_level];
				if(substr($goods_commission_per,-1)=='%'){
					$goods_commission_money=intval($goods['total_price']*substr($goods_commission_per,0,-1))/100;
					$money+=$goods_commission_money;
				}else{
					$goods_commission_money=intval($goods_commission_per*$goods['total']*100)/100;
					$money+=$goods_commission_money;
				}
				$remark['goods_commission'][]=array('goods_id'=>$goods['goodsid'],'total_price'=>$goods['total_price'],'total'=>$goods['total'],'commission_per'=>$goods_commission_per,'commission_money'=>$goods_commission_money);
			}
			if($order_price>0 && $canorder_price){
				if(substr($commission_per,-1)=='%'){
                    $order_commission_money=($order_price*substr($commission_per,0,-1))/100;
                    $money +=$order_commission_money;
				}else{
                    $order_commission_money=$commission_per*1;
                    $money +=$order_commission_money;
				}
				$remark['order_commission']=array('order_price'=>$order_price,'commission_per'=>$commission_per,'commission_money'=>$order_commission_money);
			}
			$remark['commission_money']=$money;
			if($money>0){
			    if(!$areasetting['feetype']){
                    $money -=$this->commission_order['commission_money'];
                }
                $this->commission_order['commission_money']+=$money;
				$type=$commission_level+6;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$agent['mid'],
					'buymid'=>$this->order['mid'],
					'type'=>$type,
					'ordersn'=>$this->order['ordersn'],
					'money'=>$money,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'status'=>$this->setting['is_jiesuan']?:0,
				);
				$this->insert('commission',$new_commission);
			}
			//判断是否存在区域代理
			$this->commission_order['isarea']=true;
			//此处判断分销商是否满足升级条件，如果满足则升级分销商等级
			$agent_update=array(
				'order_price +='=>$this->commission_order['order_price'],
				'order_num +='=>1,
				'commission_money +='=>$money,
			);
			$this->update('area_agent',$agent_update,array('id'=>$agent['id']));

	}
	/*
		订单完成时，把佣金状态由初始的订单待完成升级为待结算
	*/
	public function order_complete($order){
		$this->update('commission',array('status'=>1,'complete_time'=>TIMESTAMP),array('status'=>0,'ordersn'=>$order['ordersn']));
	}
	/*
		创建结算单
	*/
	public function create_balance($mid){
		if(!$mid){
			exi('请先选择要结算的会员！','error');
		}
		//获取可结算佣金
		$params=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'status'=>1,'type >='=>7);
		if($this->setting['balance_day']){
			//结算天数
			$time=TIMESTAMP-intval($this->setting['balance_day'])*86400;
			$params['complete_time <']=$time;
		}
		$commissions=$this->getall('commission',$params);
		if(!$commissions){
			exi('没有可结算的佣金！','error');
		}
		$commission_num=count($commissions);
		$money=0;
		foreach($commissions as $commission){
			$money+=$commission['money'];
		}
		//结算最低佣金检测
		if($money<$this->setting['balance_money']){
			exi('可结算佣金太少，无法结算！','error');
		}
		$new_balance=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$mid,
			'balancesn'=>get_ordersn($this->tablename('commission'),'balancesn','AC'),
			'commission_num'=>$commission_num,
			'money'=>$money,
			'createtime'=>TIMESTAMP,
			'status'=>0,
		);
		//结算手续费
		if($this->setting['balance_per']){
			$new_balance['balance_pay']=intval($new_balance['money']*$this->setting['balance_per'])/100;
		}else{
			$new_balance['balance_pay']=0;
		}
		$new_balance['final_money']=$new_balance['money']-$new_balance['balance_pay'];
		$this->insert('balance',$new_balance);
		$balance_id=pdo_insertid();
		foreach($commissions as $commission){
			$update=array(
				'status'=>2,
				'balancesn'=>$new_balance['balancesn'],
			);
			$this->update('commission',$update,array('id'=>$commission['id']));
		}
		if($post['pay_type']=='credit'){
			$typetitle='余额';
		}
		if($post['pay_type']=='wechat'){
			$typetitle='微信';
		}
		$this->model('notice')->notice_fenxiao_tixian($mid,$money,$typetitle);
		return $balance_id;
	}
	/*
		审核结算单
	*/
	public function check_balance($balance_id,$status,$remark=''){
		$update=array(
			'status'=>$status,
			'check_time'=>TIMESTAMP,
			'remark'=>$remark,
		);
		$this->update('balance',$update,array('id'=>$balance_id));
	}
	/*
		打款结算单
	*/
	public function pay_balance($balance_id,$pay_type){
		$balance=$this->get('balance',array('id'=>$balance_id,'uniacid'=>$_SESSION['uniacid']));
		if(!$balance || $balance['status']!=1){
			exi('结算单不存在或者不符合打款条件，打款失败！','error');
		}
		$pay_types=array_keys($this->pay_types);
		if(!$pay_type || !in_array($pay_type,$pay_types)){
			exi('未设置打款方式或者打款方式不合法，打款失败！','error');
		}
		$func_name='pay_balance_by_'.$pay_type;
		$trade_no=$this->$func_name($balance['mid'],$balance['final_money'],$balance['balancesn']);
		$update=array(
			'status'=>3,
			'pay_type'=>$pay_type,
			'pay_trade_no'=>$trade_no,
			'pay_time'=>TIMESTAMP,
		);
		$this->update('balance',$update,array('id'=>$balance['id']));
		$this->model('notice')->notice_fenxiao_dakuan($balance['mid'],$balance['final_money']);
		return true;
	}
	/*
		打款到余额
	*/
	protected function pay_balance_by_credit($mid,$money,$balancesn){
		return cfc('core')->member_credit($mid,'credit2',$money,true,$this->plugin_name,$remark='分销佣金打款');
	}
	/*
		打款到微信零钱
	*/
	protected function pay_balance_by_wechat($mid,$money,$balancesn){
		$params=array(
			'openid'=>$mid,
			'mch_billno'=>$balancesn,
			'money'=>$money,
			'remark'=>'代理商佣金发放',
		);
		$res=cfc('wechat_pay')->mch_pay($params);
		return $res['payment_no'];
	}
	/*
		打款到支付宝
	*/
	protected function pay_balance_by_alipay($mid,$money,$balancesn){
		exi('暂不支持打款到支付宝！','error');
	}
	/*
		打款到银行账户
	*/
	protected function pay_balance_by_union($mid,$money,$balancesn){
		exi('暂不支持打款到银行账户！','error');
	}

	public function commission_remark($remark){
		if(!$remark){
			return '';
		}
		$remark=json_decode($remark,true);
		$goods_str='';
		if($remark['goods_commission']){
			foreach($remark['goods_commission'] as $goods){
				$goods['title']=pdo_getcolumn('jy_weishop_goods',array('id'=>$goods['goods_id']),'title');
				$goods_str.="商品ID【{$goods['goods_id']}】，商品名称【{$goods['title']}】，商品数量【{$goods['total']}】，商品总价【{$goods['total_price']}】，佣金规则【{$goods['commission_per']}】，分销佣金【{$goods['commission_money']}】\n";
			}
		}else{
			$goods_str='';
		}
		$remark['level_title']=pdo_getcolumn('jy_area_agent_level',array('uniacid'=>$_SESSION['uniacid'],'level'=>$remark['level_id']),'title');
		$remark['level_title']=$remark['level_title']?:'默认等级';
		$remark_str=<<<TPL
分销商等级ID【{$remark['level_id']}】，等级名称【{$remark['level_title']}】，佣金等级【{$remark['commission_level']}】，订单总价【{$remark['order_price']}】
商品独立佣金：
{$goods_str}
订单佣金：
除去设置独立佣金的商品外订单金额【{$remark['order_commission']['order_price']}】，佣金规则【{$remark['order_commission']['commission_per']}%】，分销佣金【{$remark['order_commission']['commission_money']}】
佣金总计：【{$remark['commission_money']}】
TPL;
		return $remark_str;
	}
}